package com.example.springboot.converter;

import com.example.springboot.entry.XiaoGang;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.List;

/**
 * 自定义 converter
 *
 * @author by Mr. Li 2021/1/31 15:49
 */
public class XiaoGangMessageConverter implements HttpMessageConverter<XiaoGang> {
    public final static String xiaogangFormat = "application/X-xiaogang";

    /**
     * 都不支持读
     * 读，就是在接口处使用类似于@RequestBody注解,将数据读取进来的
     *
     * @param clazz     clazz
     * @param mediaType 内容协商类型
     * @return boolean
     */
    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return clazz.isAssignableFrom(XiaoGang.class);
    }

    /**
     * 返回该converter 支持的类型
     *
     * @return List<MediaType>
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes(xiaogangFormat);
    }

    /**
     * @param clazz        XiaoGang
     * @param inputMessage inputMessage
     * @return XiaoGang
     * @throws IOException                     io
     * @throws HttpMessageNotReadableException HttpMessageNotReadableException
     */
    @Override
    public XiaoGang read(Class<? extends XiaoGang> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(XiaoGang xiaoGang, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        // 自定义 协议
        String data = xiaoGang.getName() + ";" + xiaoGang.getAge() + ";" + "Date:" + LocalDate.now();

        // 将数据写入
        final OutputStream body = outputMessage.getBody();
        body.write(data.getBytes(StandardCharsets.UTF_8));
    }
}
